#!/usr/bin/env python

import os
import re
import wx
import app
import dialog
import printout
import component

class Main(component.Presenter):
    '''Main class
    
    @author Julot <andy.julot@gmail.com>
    @since Saturday, January 14, 2012. 09:07 AM'''
    
    PRESET_ID_CARD = 'ID Card'
    
    _image = None
    _folder = ''
    _filename = ''
    
    def __init__(self, *args, **kwargs):
        component.Presenter.__init__(self, *args, **kwargs)
        self._printData = wx.PrintData()
        self._printData.SetPrintMode(wx.PRINT_MODE_PRINTER)
        self._printData.SetQuality(wx.PRINT_QUALITY_HIGH)
        self._printDialogData = wx.PrintDialogData(self._printData)
        self._printer = wx.Printer(self._printDialogData)
        
        self.readSashPos()
        self.readImageFolder()
        self.populateOptionsPreset()
        self.readOptions()
    
    def readSashPos(self):
        config = app.Config()
        name = self.view.Name
        pos = config.ReadInt('%s/Sash' % name, -1)
        if pos != -1: self.view.splitter.SashPosition = pos
    
    def readImageFolder(self):
        config = app.Config()
        name = self.view.Name
        self._folder = config.Read('%s/ImageFolder' % name, '')
        self.populateImageNames()
    
    def readOptions(self):
        config = app.Config()
        options = self.view.options
        value = config.Read('Options/Width', '87.60')
        options.width.value = value
        value = config.Read('Options/FitWidth', '0')
        options.width.fit = True if int(value) else False
        value = config.Read('Options/Height', '55.98')
        options.height.value = value
        value = config.Read('Options/FitHeight', '0')
        options.height.fit = True if int(value) else False
        value = config.Read('Options/LeftMargin', '0')
        options.leftMargin.Value = value
        value = config.Read('Options/Rotated', '1')
        options.rotated.Value = True if int(value) else False
        value = config.Read('Options/Bordered', '1')
        options.bordered.Value = True if int(value) else False
    
    def onClose(self):
        super(Main, self).onClose()
        self.writeSashPos()
        self.writeImageFolder()
        self.writeOptions()
    
    def writeSashPos(self):
        config = app.Config()
        name = self.view.Name
        config.WriteInt('%s/Sash' % name, self.view.splitter.SashPosition)
    
    def writeImageFolder(self):
        config = app.Config()
        name = self.view.Name
        config.Write('%s/ImageFolder' % name, self._folder)
    
    def writeOptions(self):
        config = app.Config()
        options = self.view.options
        config.Write('Options/Width', '%s' % options.width.value)
        config.Write('Options/FitWidth', '1' if options.width.fit else '0')
        config.Write('Options/Height', '%s' % options.height.value)
        config.Write('Options/FitHeight', '1' if options.height.fit else '0')
        config.Write('Options/LeftMargin', options.leftMargin.Value)
        config.Write('Options/Rotated', '1' if options.rotated.Value else '0')
        config.Write('Options/Bordered', '1' if options.bordered.Value else '0')
    
    def mold(self):
        options = self.view.options
        size = wx.Size(options.width.value, options.height.value)
        fitWidth = options.width.fit
        fitHeight = options.height.fit
        leftMargin = float(options.leftMargin.Value)
        bordered = options.bordered.Value
        if options.rotated.Value: image = self._image.Rotate90()
        po = printout.Image(image, size, leftMargin, bordered, fitWidth,
                            fitHeight)
        if not self._printer.Print(self.view, po, False) \
           and self._printer.GetLastError() == wx.PRINTER_ERROR:
            s = "There was a problem printing.\n" \
              "Perhaps your current printer is not set correctly?"
            wx.MessageBox(s, "Printing Error", wx.OK)
        po.Destroy()
    
    def browse(self):
        style = wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST
        wildcard = 'Image files (*.jpg;*.png)|*.jpg;*.png'
        dialog = wx.DirDialog(self.view, 'Select a folder', self._folder,
                              style=style)
        if dialog.ShowModal() == wx.ID_OK:
            self._folder = dialog.Path
            self.populateImageNames()
        dialog.Destroy()
        
    def populateImageNames(self):
        names = []
        if self._folder:
            for name in os.listdir(self._folder):
                if re.search(r'\.(jpg|jpeg|png|gif)$', name, re.IGNORECASE):
                    names.append(name)
        self.view.names.values = names

    def preview(self, filename):
        view = self.view
        
        self._filename = filename
        path = os.path.join(self._folder, self._filename)
        try:
            self._image = wx.Image(path, wx.BITMAP_TYPE_ANY)
            view.preview.image = self._image
            view.MenuBar.file.mold.Enable()
            view.ToolBar.enableMold()
        except:
            self._image = None
            view.MenuBar.file.mold.Enable(False)
            view.ToolBar.disableMold()
            view.preview.clear()
            wx.MessageBox('Could not load image file.', 'Error')
    
    def close(self):
        self.view.Close()
    
    _about = None
    
    def showAbout(self):
        if not self._about: self._about = dialog.About(self.view)
        self._about.Center()
        self._about.Show()
        
    def populateOptionsPreset(self):
        cb = self.view.options.preset
        items = [self.PRESET_ID_CARD]
        for item in items:
            cb.Append(item, item)

    def preset(self, setting):
        options = self.view.options
        if setting == self.PRESET_ID_CARD:
            options.width.value = 87.6
            options.width.fit = False
            options.height.value = 55.98
            options.height.fit = True
            options.leftMargin.Value = '0'
            
            options.rotated.Value = True
            options.bordered.Value = True
    
    def setupPrinter(self):
        psdd = wx.PageSetupDialogData(self._printData)
        psdd.CalculatePaperSizeFromId()
        dlg = wx.PageSetupDialog(self.view, psdd)
        dlg.ShowModal()
        self._printData = wx.PrintData(dlg.PageSetupData.PrintData)
        dlg.Destroy()
    